package com.dodem.hxd.wxtools;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.cp.api.WxCpConfigStorage;
import me.chanjar.weixin.cp.api.WxCpInMemoryConfigStorage;
import me.chanjar.weixin.cp.api.WxCpMessageHandler;
import me.chanjar.weixin.cp.api.WxCpMessageRouter;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutTextMessage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;

/**
 * Servlet implementation class WxCpServlet
 */
public class WxCpServlet extends HttpServlet {

	protected WxCpInMemoryConfigStorage config;
	protected WxCpService wxCpService;
	protected WxCpMessageRouter wxCpMessageRouter;
	
	 

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);

		String msgSignature = request.getParameter("msg_signature");
		String nonce = request.getParameter("nonce");
		String timestamp = request.getParameter("timestamp");
		String echostr = request.getParameter("echostr");

		if (StringUtils.isNotBlank(echostr)) {
			if (!wxCpService.checkSignature(msgSignature, timestamp, nonce, echostr)) {
				// 消息签名不正确，说明不是公众平台发过来的消息
				response.getWriter().println("非法请求");
				return;
			}
			WxCpCryptUtil cryptUtil = new WxCpCryptUtil(config);
			String plainText = cryptUtil.decrypt(echostr);
			// 说明是一个仅仅用来验证的请求，回显echostr
			response.getWriter().println(plainText);
			 
			return;
		} else if (StringUtils.isNotBlank(msgSignature)) {
			

			WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(request.getInputStream(), config, timestamp,
					nonce, msgSignature);
			WxCpXmlOutMessage outMessage = wxCpMessageRouter.route(inMessage);
			System.out.println(inMessage.getContent());
			if (outMessage != null) {
				response.getWriter().write(outMessage.toEncryptedXml(config));
			}
			return;
		}else
		{
			response.getWriter().println("该接口为微信接口，请勿直接访问！");
		}

//		super.service(request, response);
	}

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WxCpServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		config = new WxCpInMemoryConfigStorage();

		config.setCorpId("wx27362885178c643b"); // 设置微信企业号的appid
		config.setCorpSecret("U_nBClHfQGmbEPYB4y2eYoThgqzLhUkxRYWXMSClXdQjYig3DuYE1I076DaKfQzs"); // 设置微信企业号的app
																									// corpSecret
		config.setAgentId("2"); // 设置微信企业号应用ID
		config.setToken("xlssxj"); // 设置微信企业号应用的token
		config.setAesKey("gHoO578nMSsegY0CrxwKKOcWXfKgPap1gDoaVA3oZgd"); // 设置微信企业号应用的EncodingAESKey

		wxCpService = new WxCpServiceImpl();
		wxCpService.setWxCpConfigStorage(config);
 
		WxCpMessageHandler handler = new WxCpMessageHandler() {

			public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context,
					WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
				WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("测试加密消息").fromUser(wxMessage.getToUserName())
						.toUser(wxMessage.getFromUserName()).build();
				return m;
			}

		};

		wxCpMessageRouter = new WxCpMessageRouter(wxCpService);
		wxCpMessageRouter.rule().async(false).content("哈哈") // 拦截内容为“哈哈”的消息
				.handler(handler).end();

	}

}
